package com.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;

public class DateUtil
{
    //计算从当前算起的n年后的日期
    public static Date calculationDate( long years )
    {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime future = now.plusYears( years );
        ZoneId zoneId = ZoneId.systemDefault();
        ZonedDateTime zdt = future.atZone(zoneId);
        Date date = Date.from(zdt.toInstant());

        return date;
    }

    //计算给定日期的的n年后的日期
    public static Date calculationDate( Date date , long years )
    {
        ZoneId zoneId = ZoneId.systemDefault();
        Instant instant = date.toInstant();
        LocalDateTime oldDate = instant.atZone(zoneId).toLocalDateTime();
        LocalDateTime future = oldDate.plusYears( years );
        ZonedDateTime zdt = future.atZone(zoneId);
        Date newDate = Date.from(zdt.toInstant());

        return newDate;
    }

    //将datetime字符串转换为时间
    public static Date strToDateTime( String str )
    {
        Date date = null;
        SimpleDateFormat sf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"  );
        try
        {
            date = sf.parse( str );
        }
        catch ( ParseException e )
        {
            System.out.println( "日期转换出错" );
            e.printStackTrace();
        }

        return date;
    }

    public static Date strToDate( String str )
    {
        Date date = null;
        SimpleDateFormat sf = new SimpleDateFormat( "yyyy-MM-dd"  );
        try
        {
            date = sf.parse( str );
        }
        catch ( ParseException e )
        {
            System.out.println( "日期转换出错" );
            e.printStackTrace();
        }

        return date;
    }

    //将date对象转换为时间字符串
    public static String dateToStr( Date date )
    {
        String str = "";
        SimpleDateFormat sf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
        str = sf.format( date );

        return str;
    }
}
